<template>
  <div class="points-goods-container">
    <!-- 标题和操作按钮 -->
    <div class="header-section">
      <h2>积分商品管理</h2>
      <el-button
          type="primary"
          @click="openAddDialog"
          style="background-color: #409EFF; border-color: #409EFF;"
      >
        <el-icon><Plus /></el-icon>
        新增商品
      </el-button>
    </div>

    <!-- 搜索卡片 -->
    <el-card class="search-card" shadow="hover">
      <el-form :inline="true">
        <el-form-item label="商品名称">
          <el-input placeholder="请输入商品名称" v-model="searchParams.goodsName" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchParams.isActive" placeholder="请选择状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="上架" :value="1"></el-option>
            <el-option label="下架" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadGoodsList" style="background-color: #409EFF; border-color: #409EFF;">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="goodsList" border stripe v-loading="loading">
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
        <el-table-column label="商品图片" align="center" width="120">
          <template #default="scope">
            <el-image
                style="width: 80px; height: 80px"
                :src="scope.row.coverUrl"
                :preview-src-list="[scope.row.coverUrl]"
                fit="cover"
                v-if="scope.row.coverUrl"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="pointsRequired" label="所需积分" align="center" width="100"></el-table-column>
        <el-table-column prop="stockQuantity" label="库存" align="center" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isActive === 1 ? 'success' : 'danger'">
              {{ scope.row.isActive === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
                size="small"
                @click="editGoods(scope.row)"
                style="color: #409EFF;"
                link
            >
              编辑
            </el-button>
            <el-button
                size="small"
                @click="toggleStatus(scope.row)"
                :style="{color: scope.row.isActive === 1 ? '#f56c6c' : '#67c23a'}"
                link
            >
              {{ scope.row.isActive === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="deleteGoods(scope.row.goodsId)"
                link
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form ref="goodsFormRef" :model="goodsForm" label-width="100px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="goodsForm.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品图片" prop="coverUrl">
              <el-upload
                  class="avatar-uploader"
                  action="/api/upload"
                  :show-file-list="false"
                  :on-success="handleUploadSuccess"
                  :before-upload="beforeUpload"
              >
                <img v-if="goodsForm.coverUrl" :src="goodsForm.coverUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需积分" prop="pointsRequired">
              <el-input-number v-model="goodsForm.pointsRequired" :min="1" :max="999999" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stockQuantity">
              <el-input-number v-model="goodsForm.stockQuantity" :min="0" :max="999999" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isActive">
              <el-radio-group v-model="goodsForm.isActive">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品描述" prop="description">
              <el-input
                  v-model="goodsForm.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入商品描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" style="background-color: #409EFF; border-color: #409EFF;">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 设置axios基础URL和请求拦截器
axios.defaults.baseURL = 'http://localhost:8080'

// 添加请求拦截器
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('adminToken')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 搜索参数
const searchParams = ref({
  goodsName: '',
  isActive: ''
})

// 分页参数
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 商品列表数据
const goodsList = ref([])
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增商品')
const goodsFormRef = ref(null)
const goodsForm = ref({
  goodsId: null,
  goodsName: '',
  coverUrl: '',
  description: '',
  pointsRequired: 100,
  stockQuantity: 10,
  isActive: 1
})

// 表单验证规则
const rules = {
  goodsName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  pointsRequired: [
    { required: true, message: '请输入所需积分', trigger: 'blur' },
    { type: 'number', min: 1, message: '积分必须大于0', trigger: 'blur' }
  ],
  stockQuantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' }
  ],
  isActive: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 加载商品列表
const loadGoodsList = async () => {
  try {
    loading.value = true

    // 构建查询参数，过滤掉空值
    const params = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.size,
      ...Object.fromEntries(
          Object.entries(searchParams.value)
              .filter(([_, value]) => value !== '' && value !== null)
      )
    }

    const res = await axios.get('/api/v1/points-goods/list', { params })
    if (res.data && res.data.code === 2000) {
      goodsList.value = res.data.data.list || res.data.data
      pagination.value.total = res.data.data.total || res.data.total
    } else {
      ElMessage.error(res.data?.msg || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error(error.response?.data?.msg || '获取商品列表失败')

    // 如果未授权，跳转到登录页
    if (error.response?.status === 401) {
      localStorage.removeItem('adminToken')
      window.location.href = '/login'
    }
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    goodsName: '',
    isActive: ''
  }
  pagination.value.current = 1
  loadGoodsList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.value.size = size
  loadGoodsList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.value.current = current
  loadGoodsList()
}

// 打开新增弹窗
const openAddDialog = () => {
  dialogTitle.value = '新增商品'
  goodsForm.value = {
    goodsId: null,
    goodsName: '',
    coverUrl: '',
    description: '',
    pointsRequired: 100,
    stockQuantity: 10,
    isActive: 1
  }
  dialogVisible.value = true
}

// 编辑商品
const editGoods = (row) => {
  dialogTitle.value = '编辑商品'
  goodsForm.value = {
    goodsId: row.goodsId,
    goodsName: row.goodsName,
    coverUrl: row.coverUrl,
    description: row.description,
    pointsRequired: row.pointsRequired,
    stockQuantity: row.stockQuantity,
    isActive: row.isActive
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await goodsFormRef.value.validate()

    let res
    if (goodsForm.value.goodsId) {
      // 更新
      const updateParam = {
        goodsId: goodsForm.value.goodsId,
        goodsName: goodsForm.value.goodsName,
        coverUrl: goodsForm.value.coverUrl,
        description: goodsForm.value.description,
        pointsRequired: goodsForm.value.pointsRequired,
        stockQuantity: goodsForm.value.stockQuantity,
        isActive: goodsForm.value.isActive
      }
      res = await axios.post('/api/v1/points-goods/update', updateParam)
    } else {
      // 新增
      res = await axios.post('/api/v1/points-goods/add', goodsForm.value)
    }

    if (res.data.code === 2000) {
      ElMessage.success(dialogTitle.value + '成功')
      dialogVisible.value = false
      loadGoodsList()
    } else {
      ElMessage.error(res.data.msg || dialogTitle.value + '失败')
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error.response && error.response.data && error.response.data.msg) {
      ElMessage.error(error.response.data.msg)
    }
  }
}

// 切换状态
const toggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要${row.isActive === 1 ? '下架' : '上架'}该商品吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const res = await axios.post('/api/v1/points-goods/toggle-status', { goodsId: row.goodsId })

    if (res.data.code === 2000) {
      ElMessage.success('状态更新成功')
      // 直接更新当前行的状态，避免重新加载整个列表
      row.isActive = row.isActive === 1 ? 0 : 1
    } else {
      ElMessage.error(res.data.msg || '状态更新失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态更新失败:', error)
      ElMessage.error(error.response?.data?.msg || '状态更新失败')
    }
  }
}

// 删除商品
const deleteGoods = async (goodsId) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await axios.post('/api/v1/points-goods/delete', [goodsId])
    if (res.data.code === 2000) {
      ElMessage.success('删除成功')
      loadGoodsList()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 图片上传成功处理
const handleUploadSuccess = (response) => {
  if (response.code === 2000) {
    goodsForm.value.coverUrl = response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 图片上传前校验
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }

  return isJpgOrPng && isLt2M
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 初始化
onMounted(() => {
  loadGoodsList()
})
</script>

<style scoped>
.points-goods-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-section h2 {
  color: #304156;
  font-size: 20px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 4px;
  border: none;
  background-color: #fff;
}

.table-card {
  border-radius: 4px;
  border: none;
  background-color: #fff;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  width: 100%;
}

.el-tag {
  margin-right: 5px;
}

.el-form-item :deep(.el-form-item__label) {
  color: #606266;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>